package com.su.controller;

import com.su.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;


/**
 * 文件上传下载
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class FileController {
    @Value("${fileLocation.path}")
    private String filePath;

    /**
     * 文件上传
     *
     * @param file
     * @param
     * @return
     */
    @PostMapping("/upload")
    public R<String> fileUpload(MultipartFile file) {

        //文件原始名
        String filename = file.getOriginalFilename();
        //文件后缀名
        String suffix = filename.substring(filename.lastIndexOf("."));
        //获取随机文件名
        UUID path = UUID.randomUUID();
        //重新组合
        String fileName = path + suffix;
        //创建文件夹
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            //将文件存到指定位置
            file.transferTo(new File(filePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    /**
     * 下载文件
     *
     * @param name
     * @param resp
     * @return
     */
    @GetMapping("/download")
    public void fileDownload(String name, HttpServletResponse resp) {
        try {
            FileInputStream fis = new FileInputStream(new File(filePath + name));
            ServletOutputStream outputStream = resp.getOutputStream();
            int len;
            byte[] bytes = new byte[1024 * 8];
            while ((len = fis.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            fis.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
